package com.example.elmmerchants.Create_Shop;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.example.elmmerchants.Badiu_OCR.AccessToken;
import com.example.elmmerchants.Badiu_OCR.Base64Util;
import com.example.elmmerchants.Badiu_OCR.HttpUtil;
import com.example.elmmerchants.R;
import com.example.elmmerchants.SQL.Connection_SQL;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Upload_Food_Business_Licence_Picture_Page extends AppCompatActivity {

    Button upload_photo;
    //BottomSheetBehavior bottomSheetBehavior;

    String user_email;
    String image_string = "";
    Uri image1;
    String[] json_key = {"经营者名称", "经营场所", "日常监督管理机构", "日常监督管理人员", "签发日期", "经营项目", "有效期至", "许可证编号", "法定代表人", "社会信用代码", "住所", "发证机关", "主体业态", "签发人"};
    Map<String, String> json = new HashMap<>();
    boolean is_upload_data = false;
    String word_res;
    AlertDialog dialog;

    private class Loading_Data_Thread extends Thread {

        byte[] imageBytes;

        public Loading_Data_Thread(byte[] imageBytes) {
            this.imageBytes = imageBytes;
        }

        @Override
        public void run() {
            String resultden = accurateBasic(imageBytes);
            int num = 0;
            System.out.println(resultden);
            while (num <= 3 && resultden.indexOf("error_code") != -1) {
                resultden = accurateBasic(imageBytes);
                num += 1;
            }
            if (Build.VERSION.SDK_INT >= 23) {
                int REQUEST_CODE_CONTACT = 101;
                String[] permissions = {
                        Manifest.permission.WRITE_EXTERNAL_STORAGE};
                //验证是否许可权限
                for (String str : permissions) {
                    if (Upload_Food_Business_Licence_Picture_Page.this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                        //申请权限
                        Upload_Food_Business_Licence_Picture_Page.this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                        return;
                    } else {
                        int finalNum = num;
                        String finalResultden = resultden;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (finalNum >= 3 && finalResultden.indexOf("error_code") != -1) {
                                    dialog.dismiss();
                                    json.clear();
                                    Toast.makeText(Upload_Food_Business_Licence_Picture_Page.this, "无法识别该食品经营许可证", Toast.LENGTH_SHORT).show();
                                }
                                else {
                                    try {
                                        JSONObject object = new JSONObject(finalResultden);
                                        word_res = object.get("words_result").toString();
                                        for (int i = 0; i < json_key.length; i++) {
                                            JSONObject object_1 = new JSONObject(word_res);
                                            String word_res_2 = object_1.get(json_key[i]).toString();
                                            JSONArray object_2 = new JSONArray(word_res_2);
                                            if (object_2.length() != 0) {
                                                String word_res_3 = object_2.get(0).toString();
                                                JSONObject object_3 = new JSONObject(word_res_3);
                                                json.put(json_key[i], object_3.get("word").toString());
                                            }
                                            else {
                                                json.put(json_key[i], "");
                                            }
                                        }
                                        for (String key : json.keySet()) {
                                            System.out.println(key + ": " + json.get(key));
                                        }

                                        is_upload_data = false;

                                        ExecutorService executorService = Executors.newSingleThreadExecutor();
                                        executorService.execute(() -> {
                                            try {
                                                Connection_SQL connectionSql = new Connection_SQL();
                                                Connection connection = connectionSql.connection();
                                                Blob blobUpload = connection.createBlob();
                                                blobUpload.setBytes(1, imageBytes);
                                                String sql = "update `merchant` set food_business_licence_picture = ? where email = ?";
                                                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                                                preparedStatement.setBlob(1, blobUpload);
                                                preparedStatement.setString(2, user_email);
                                                preparedStatement.executeUpdate();

                                                String sql2 = "INSERT INTO `elm`.`merchant_food_business_licence`(number, business_name, code, representative_person, live_where, business_place, sale_what, business_scope, validity_date, license_number, email, supervisory_agency, supervisory_person, report_phone_number, issuer) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
                                                preparedStatement = connection.prepareStatement(sql2);
                                                preparedStatement.setString(1, "");
                                                preparedStatement.setString(2, json.get("经营者名称"));
                                                preparedStatement.setString(3, json.get("社会信用代码"));
                                                preparedStatement.setString(4, json.get("法定代表人"));
                                                preparedStatement.setString(5, json.get("住所"));
                                                preparedStatement.setString(6, json.get("经营场所"));
                                                preparedStatement.setString(7, json.get("主体业态"));
                                                preparedStatement.setString(8, json.get("经营项目"));
                                                preparedStatement.setString(9, json.get("有效期至"));
                                                preparedStatement.setString(10, json.get("许可证编号"));
                                                preparedStatement.setString(11, user_email);
                                                preparedStatement.setString(12, json.get("日常监督管理机构"));
                                                preparedStatement.setString(13, json.get("日常监督管理人员"));
                                                preparedStatement.setString(14, "");
                                                preparedStatement.setString(15, json.get("签发人"));
                                                preparedStatement.executeUpdate();

                                                is_upload_data = true;
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }

                                            while (!is_upload_data) {
                                                try {
                                                    Thread.sleep(1);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }

                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    dialog.dismiss();
                                                    Toast.makeText(Upload_Food_Business_Licence_Picture_Page.this, "已成功上传", Toast.LENGTH_SHORT).show();
                                                    Intent intent1 = new Intent(Upload_Food_Business_Licence_Picture_Page.this, Qualification_Information_Page.class);
                                                    intent1.putExtra("food_business_licence_pic", "已上传");
                                                    setResult(3, intent1);
                                                    finish();
                                                }
                                            });
                                        });
                                    }catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
    }

    private final ActivityResultLauncher<Intent> food_licence_activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult o) {
            if (o.getResultCode() == RESULT_OK) {
                if (o.getData() != null) {
                    image1 = o.getData().getData();

                    try {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), image1);

                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        byte[] imageBytes = baos.toByteArray();

                        set_dialog();

                        Loading_Data_Thread loadingDataThread = new Loading_Data_Thread(imageBytes);
                        loadingDataThread.start();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            else {
                Toast.makeText(Upload_Food_Business_Licence_Picture_Page.this, "请选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_food_business_licence_picture_page);

        user_email = getIntent().getStringExtra("user_email");

        upload_photo = findViewById(R.id.upload_photo);

        upload_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                food_licence_activityResultLauncher.launch(intent);
            }
        });
    }

    public String accurateBasic(byte[] imageData) {
        // 请求url
        AccessToken accessToken1= new AccessToken();
        String token = accessToken1.getAuth();


        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/food_business_license";
        try {
            String imgStr = Base64Util.encode(imageData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = token;

            String result = HttpUtil.post(url, accessToken, param);

            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void set_dialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Upload_Food_Business_Licence_Picture_Page.this);
        LayoutInflater inflater1 = LayoutInflater.from(Upload_Food_Business_Licence_Picture_Page.this);
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }
}